package com.gitee.starblues.example.jpa.config;

import com.gitee.starblues.example.jpa.config.prop.QuartzJobProp;
import com.gitee.starblues.example.jpa.service.quartz.DatabaseInsertJob;
import lombok.AllArgsConstructor;
import org.quartz.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * quartz 配置
 * @author starBlues
 * @version 2.4.3
 */
@Configuration
@AllArgsConstructor
public class QuartzJobConfig {

    private final QuartzJobProp quartzJobProp;
    private final ApplicationContext applicationContext;


    @Bean
    public JobDetail databaseInsertJob(){
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put(DatabaseInsertJob.APPLICATION_CONTEXT, applicationContext);
        return JobBuilder.newJob(DatabaseInsertJob.class)
                .storeDurably()
                .setJobData(jobDataMap)
                .build();
    }

    @Bean
    public Trigger trigger1(){
        CronScheduleBuilder cronScheduleBuilder =
                CronScheduleBuilder.cronSchedule(quartzJobProp.getDatabaseInsertJobCron());
        Long databaseInsertJobDelaySec = quartzJobProp.getDatabaseInsertJobDelaySec();
        return TriggerBuilder.newTrigger()
                .forJob(databaseInsertJob())
                .withSchedule(cronScheduleBuilder)
                .startAt(new Date(System.currentTimeMillis() + (databaseInsertJobDelaySec * 1000)))
                .build();
    }

}
